package com.oppo.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oppo.bean.CarBean;
import com.oppo.bean.ProductBean;
import com.oppo.service.impl.AddCarItemService;
import com.oppo.tools.MyTools;

@WebServlet("/AddCarItemControl")
public class AddCarItemControl extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String user_id = request.getSession().getAttribute("user_id").toString();
		if(user_id != null && !user_id.equals("")){
			String product_color = request.getParameter("product_color");
			String product_model = request.getParameter("product_model");
			String product_count = request.getParameter("product_count");
			ProductBean pb = new ProductBean();
			CarBean cb = new CarBean();
			pb.setProduct_color(product_color);//商品颜色
			pb.setProduct_model(product_model);//商品型号，通过这两个字段确定商品
			
			cb.setProduct_count(new Long(product_count));//设置商品数量
			cb.setUser_id(new Long(user_id));//设置用户ID
			//先获取要加入购物车商品的信息
			List<ProductBean> list = MyTools.getNewInstance(AddCarItemService.class).getProductInfo(pb);
			if(list != null && list.size() > 0) {
				Long id = list.get(0).getProduct_id();
				Long price = list.get(0).getProduct_price() * cb.getProduct_count();
				cb.setProduct_id(id);//设置商品ID
				cb.setProduct_allprice(price);//该条记录的总价
			}
			//获取购物车信息
			List<CarBean> cblist = MyTools.getNewInstance(AddCarItemService.class).getCarTInfo(cb);
			int i = 0;
			if(cblist == null|| cblist.size() == 0) {//先前未添加该商品的情况
				i = MyTools.getNewInstance(AddCarItemService.class).getAddCarInfo(cb);//直接插入
			}else {//之前添加过了
				Long newCount = cblist.get(0).getProduct_count() + cb.getProduct_count();
				cb.setProduct_count(newCount);
				Long newAllPrice = new Long(newCount * list.get(0).getProduct_price());
				cb.setProduct_allprice(newAllPrice);
				Long newCar_id = cblist.get(0).getCar_id();
				cb.setCar_id(newCar_id);
				i = MyTools.getNewInstance(AddCarItemService.class).updateCarInfo(cb);//更新
			}
			if(i > 0) {
				String str = "true";
				MyTools.logRootLogger.info(user_id + "将型号" + product_model +" "+ product_color +"加入购物车！");
				PrintWriter pw = response.getWriter();
				pw.write(str);
				pw.flush();
			}
		}else{
			PrintWriter pw = response.getWriter();
			pw.write("nulluser");
			pw.flush();
		}
		
	}

}
